package com.eduadmin.controller;

import com.eduadmin.entity.CourseDivide;
import com.eduadmin.entity.Page;
import com.eduadmin.entity.TotalDivide;
import com.eduadmin.service.ICourseDivideService;
import com.eduadmin.service.ITotalDivideService;
import com.eduadmin.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
public class CourseDivideController {
    private final ICourseDivideService courseDivideService;
    @Autowired
    public CourseDivideController(ICourseDivideService courseDivideService) {
        this.courseDivideService = courseDivideService;
    }
    // 分页查询班级学科一分段记录
    @RequestMapping(value = "getQueCourseDivide")
    @ResponseBody
    public Map<String, Object> getQueTotalDivide(
            @RequestParam(value = "page", required = false) String page,
            @RequestParam(value = "rows", required = false) String rows,
            @RequestParam("gradeName") String gradeName,
            @RequestParam("semesterName") String semesterName,
            @RequestParam("examName") String examName,
            @RequestParam("categoryName") String categoryName,
            @RequestParam("courseEnName") String courseEnName){

        Page pageBean = new Page(Integer.parseInt(page), Integer.parseInt(rows));
        Map<String, Object> reMap = new HashMap<>();                 //查询结果map
        Map<String, Object> paraMap = new HashMap<>();           //查询参数map
        paraMap.put("offset", pageBean.getOffset());
        paraMap.put("rows", pageBean.getRows());
        paraMap.put("gradeName",gradeName);
        paraMap.put("semesterName",semesterName);
        paraMap.put("examName",examName);
        paraMap.put("categoryName",categoryName);
        paraMap.put("courseEnName",courseEnName);
        List<CourseDivide> courseDivideList=courseDivideService.getAllCourseDivideByParams(paraMap);
        paraMap.clear();
        paraMap.put("gradeName",gradeName);
        paraMap.put("semesterName",semesterName);
        paraMap.put("examName",examName);
        paraMap.put("categoryName",categoryName);
        paraMap.put("courseEnName",courseEnName);
        int total = courseDivideService.getAllCourseDivideNumberByParams(paraMap);
        reMap.put("rows", courseDivideList);
        reMap.put("total", total);
        return reMap;
    }
    // 导出到excel
    @RequestMapping("exportCourseDivideData")
    public void exportTotalDivideData(@RequestParam("gradeName") String gradeName,
                                      @RequestParam("semesterName") String semesterName,
                                      @RequestParam("examName") String examName,
                                      @RequestParam("categoryName") String categoryName,
                                      @RequestParam("courseEnName") String courseEnName,
                                      HttpServletResponse response){
        Map<String, Object> paraMap = new HashMap<>();           //查询参数map
        paraMap.put("gradeName",gradeName);
        paraMap.put("semesterName",semesterName);
        paraMap.put("examName",examName);
        paraMap.put("categoryName",categoryName);
        paraMap.put("courseEnName",courseEnName);
        List<CourseDivide> courseDivideList=courseDivideService.getAllCourseDivideForChartsByParams(paraMap); //返回值已经按照班级升序，学科成绩降序排序
        HashMap<String,String> courseMap=new HashMap<String,String>(){{
            put("chinese","语文");
            put("maths","数学");
            put("english","英语");
            put("physics","物理");
            put("history","历史");
            put("chemistry","化学");
            put("biology","生物");
            put("politics","政治");
            put("geography","地理");
            put("sports","体育");
        }};
        String courseChName=courseMap.get(courseEnName);
        try {
            ExcelUtils.export2Web(response, gradeName+semesterName+examName+courseChName+"一分段表", courseChName+"一分段表", CourseDivide.class, courseDivideList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 图表应用：班级学科成绩分布
    @RequestMapping(value = "getCourseDivideChartData")
    @ResponseBody
    public Map<String,Object> getCourseDivideChartData(@RequestParam("gradeName") String gradeName,
                                                       @RequestParam("semesterName") String semesterName,
                                                       @RequestParam("examName") String examName,
                                                       @RequestParam("categoryName") String categoryName,
                                                       @RequestParam("courseEnName") String courseEnName){
        Map<String, Object> paraMap = new HashMap<>();           //查询参数map
        paraMap.put("gradeName",gradeName);
        paraMap.put("semesterName",semesterName);
        paraMap.put("examName",examName);
        paraMap.put("categoryName",categoryName);
        paraMap.put("courseEnName",courseEnName);
        List<CourseDivide> courseDivideList=courseDivideService.getAllCourseDivideForChartsByParams(paraMap); //返回值已经按照班级升序，学科成绩降序排序

        // 计算学科总分的分数区间[minn,maxn]，[班级名称]，[[[学科总分段1,人数1占比],[学科总分段2，人数2占比]],[[,],[,]]]数据
        List<String> forLegendData=new ArrayList();
        int maxn=0,minn=100000;
        for(int i=0;i<courseDivideList.size();i++){
            int t=courseDivideList.get(i).getCourseDivide();
            if (maxn<t) maxn=t;
            if (minn>t) minn=t;
            String tTeamName=courseDivideList.get(i).getTeamName();
            boolean tag=true;
            for (int j=0;j<forLegendData.size();j++){
                if (forLegendData.get(j).equals(tTeamName)) {tag=false;break;}
            }
            if (tag) {forLegendData.add(tTeamName);};
        }
        // 获取班级实考总人数。
        int studentTotal[]=new int[100];
        int si=0;
        for(int i=0;i<courseDivideList.size();i++){
            if (courseDivideList.get(i).getCourseDivide()==minn) {
                studentTotal[si]=courseDivideList.get(i).getTeamCourseStudentNumber();si++;} //最小值所在记录中有第si班的学生人数。
        }

        // 获取每班的班级总分（共分为m段）百分比
        int m=4;
        int step=Math.round((maxn-minn+1)/m);// 取整数分数为一段
        Map<String,Object> forSeriesData=new HashMap<>();
        for (int i=0;i<forLegendData.size();i++){
            List<float[]> t0=new ArrayList<>();
            String tTeamName=forLegendData.get(i);
            // 起点为i*(maxn-minn)
            int j=i*(maxn-minn+1);
            for (int k=0;k<m;k++){
                float tx=courseDivideList.get(j).getCourseDivide();
                float ty=courseDivideList.get(j).getTeamCourseStudentNumber();
                if (k==0) { //班级起始点
                    float[] t1=new float[2];
                    t1[0]=tx;
                    if (studentTotal[i]>0) //防止除数为0
                        t1[1]=Float.parseFloat(new Formatter().format("%.2f", ty/studentTotal[i]*100).toString());//保留小数点后两位
                    else t1[1]=0;
                    t0.add(t1);
                } else { //中间段
                    float[] t1=new float[2];
                    ty-=courseDivideList.get(j-step).getTeamCourseStudentNumber();
                    t1[0]=tx;
                    if (studentTotal[i]>0) //防止除数为0
                        t1[1]=Float.parseFloat(new Formatter().format("%.2f", ty/studentTotal[i]*100).toString());//保留小数点后两位
                    else t1[1]=0;
                    t0.add(t1);
                }
                j+=step;
            }
            // 班级终点
            j-=step;//最后一段的起点。
            float[] t1=new float[2];
            float tx=courseDivideList.get((maxn-minn+1)*(i+1)-1).getCourseDivide();
            float ty=courseDivideList.get((maxn-minn+1)*(i+1)-1).getTeamCourseStudentNumber()-courseDivideList.get(j).getTeamCourseStudentNumber();
            t1[0]=tx;
            if(studentTotal[i]>0)
                t1[1]=Float.parseFloat(new Formatter().format("%.2f", ty/studentTotal[i]*100).toString());//保留小数点后两位
            else t1[1]=0;
            t0.add(t1);
            forSeriesData.put(tTeamName,t0);
        }
        Map<String,Object> res=new HashMap<>();
        res.put("forLegendData",forLegendData);
        res.put("forSeriesData",forSeriesData);
        return res;
    }
}
